using Microsoft.EntityFrameworkCore;
using DeathReportManagement.Data;
using DeathReportManagement.Models;

namespace DeathReportManagement.Services;

public class Icd10Service
{
    private readonly DeathReportContext _context;

    public Icd10Service(DeathReportContext context)
    {
        _context = context;
    }

    /// <summary>
    /// 搜索ICD10编码
    /// </summary>
    /// <param name="keyword">关键词（编码或名称）</param>
    /// <param name="limit">返回数量限制</param>
    /// <returns>ICD10编码列表</returns>
    public async Task<List<Icd10>> SearchAsync(string keyword, int limit = 20)
    {
        if (string.IsNullOrWhiteSpace(keyword))
        {
            return new List<Icd10>();
        }

        keyword = keyword.Trim();

        var query = _context.Icd10s
            .Where(i => i.IsActive && 
                       (i.Code.Contains(keyword) || 
                        i.Name.Contains(keyword)))
            .OrderBy(i => i.Code)
            .Take(limit);

        return await query.ToListAsync();
    }

    /// <summary>
    /// 根据编码获取ICD10信息
    /// </summary>
    /// <param name="code">ICD10编码</param>
    /// <returns>ICD10信息</returns>
    public async Task<Icd10?> GetByCodeAsync(string code)
    {
        if (string.IsNullOrWhiteSpace(code))
        {
            return null;
        }

        return await _context.Icd10s
            .FirstOrDefaultAsync(i => i.Code == code.Trim() && i.IsActive);
    }

    /// <summary>
    /// 获取所有ICD10编码（分页）
    /// </summary>
    /// <param name="page">页码</param>
    /// <param name="pageSize">页大小</param>
    /// <returns>ICD10编码列表</returns>
    public async Task<List<Icd10>> GetAllAsync(int page = 1, int pageSize = 50)
    {
        return await _context.Icd10s
            .Where(i => i.IsActive)
            .OrderBy(i => i.Code)
            .Skip((page - 1) * pageSize)
            .Take(pageSize)
            .ToListAsync();
    }

    /// <summary>
    /// 根据分类获取ICD10编码
    /// </summary>
    /// <param name="category">分类</param>
    /// <returns>ICD10编码列表</returns>
    public async Task<List<Icd10>> GetByCategoryAsync(string category)
    {
        if (string.IsNullOrWhiteSpace(category))
        {
            return new List<Icd10>();
        }

        return await _context.Icd10s
            .Where(i => i.IsActive && i.Category == category)
            .OrderBy(i => i.Code)
            .ToListAsync();
    }
}